package com.ruoyi.erp.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.*;
import com.ruoyi.erp.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.erp.controller.LedyFeeCheckinController.initAccvouch;
import static com.ruoyi.erp.controller.LedyFeeCheckinController.insertUser;

/**
 * 开票费用凭证Controller
 *
 * @author ztj
 * @date 2023-07-05
 */
@RestController
@RequestMapping("/erp/tax")
public class LedyTaxController extends BaseController {
    @Autowired
    private ILedyTaxService ledyTaxService;
    @Autowired
    private IGlAccvouchService glAccvouchService;
    @Autowired
    private ILedyBacFeeConfigService configService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private IGlCashtableService cashtableService;


    @Log(title = "凭证生成", businessType = BusinessType.IMPORT)
    @GetMapping("/sync/{ids}/{type}")
    public AjaxResult faSync(@PathVariable Long[] ids, @PathVariable String type, LedyTax ledyFeeCheckin) {
        List<LedyTax> checkins = ledyTaxService.selectLedyTaxByIds(ids);
        GlAccvouch accvouch = new GlAccvouch();
        GlAccvouch accvouchQuery = new GlAccvouch();
        List<LedyBacFeeConfig> confList = initAccvouch(ledyFeeCheckin.getDbillDate(), "feetax", glAccvouchService, configService, type, accvouch, accvouchQuery);
        final int[] i = {0};
//        for (LedyTax tax : checkins) {
//            if (StringUtils.isEmpty(tax.getAmountStatus())) {
//                return error("发票：" + tax.getRecordNumber() + "收款状态不能为空，请手动维护！");
//            }
//        }
        GlAccvouch accvouch100200 = new GlAccvouch();
        checkins.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getRemark()) && item.getRemark().contains("收案编号:")) {
                String number = item.getRemark().substring(5, 22);
                insertUser(i, glAccvouchService, customerService, type, accvouch, accvouchQuery, number, item.getBuyName());
            }else {
                insertUser(i, glAccvouchService, customerService, type, accvouch, accvouchQuery, "", item.getBuyName());
            }
            String cusId = accvouch.getCcusId();
            confList.forEach(conf -> {
                i[0]++;
                if (!conf.getAuxiliaryTerm().contains("ccusId")) {
                    accvouch.setCcusId(null);
                } else {
                    accvouch.setCcusId(cusId);
                }
                accvouch.setInid(Long.parseLong(i[0] + ""));
                accvouch.setCcode(conf.getCcode());
                accvouch.setMd("0");
                accvouch.setMc("0");
                accvouch.setCdigest(item.getBuyName() + item.getRemark());
                accvouch.setcCashItem(conf.getCashDesc());
                accvouch.setCcodeEqual(confList.stream().map(s -> {
                    if (!s.getCcode().equals(conf.getCcode()) && !s.getRecordCate().equals(conf.getRecordCate())) {
                        if (s.getRecordCate().equals("借")) {
                            if (!item.getGoodsName().contains(s.getRemark()) && !s.getCcode().equals("100200")) {
                                return null;
                            }
                            if (s.getCcode().equals("100200") && (item.getGoodsName().contains("仲裁员报酬") || item.getGoodsName().contains("机构费用"))) {
                                return null;
                            }
                            if (item.getSumMoney().compareTo(new BigDecimal(0)) <= 0) {
                                return null;
                            }
                        } else {
                            if (!item.getGoodsName().contains(s.getRemark())) {
                                return null;
                            }
                            if (item.getSumMoney().compareTo(new BigDecimal(0)) <= 0) {
                                return null;
                            }
                        }
                        return s.getCcode();
                    } else return null;
                }).distinct().collect(Collectors.joining(",")).replaceAll("null,", "").replace(",null", ""));
                accvouch.setCcodeexchEqual(accvouch.getCcodeEqual());
                if (conf.getRecordCate().equals("借")) {
                    if (conf.getCcode().equals("100200") && !item.getGoodsName().contains("仲裁员报酬") && !item.getGoodsName().contains("机构费用")) {
                        if (StringUtils.isEmpty(accvouch100200.getCcode())) {
                            accvouch.setMd(item.getTaxPriceAmount().toString());
                            if (type.equals("1"))
                                BeanUtil.copyProperties(accvouch, accvouch100200);
                        } else {
                            accvouch100200.setMd(item.getTaxPriceAmount().add(new BigDecimal(accvouch100200.getMd())).toString());
                            i[0]--;
                            return;
                        }
                    }
                    if (item.getGoodsName().contains(conf.getRemark())) {
                        accvouch.setMd(item.getTaxPriceAmount().toString());
                    }
                } else {
                    if (item.getGoodsName().contains(conf.getRemark())) {
//                        if (!item.getGoodsName().contains("仲裁员报酬") && !item.getGoodsName().contains("机构费用")) {
//                            if(StringUtils.isEmpty(accvouch100200.getCcodeEqual())){
//                                accvouch100200.setCcodeexchEqual(conf.getCcode());
//                            }else {
//                                accvouch100200.setCcodeexchEqual(accvouch100200.getCcodeEqual()+","+conf.getCcode());
//                            }
//                        }

                        if (conf.getAmount().equals("sumMoney"))
                            accvouch.setMc(item.getSumMoney().toString());
                        else
                            accvouch.setMc(item.getTaxAmount().toString());
                    }
                }
                if (new BigDecimal(accvouch.getMc()).compareTo(new BigDecimal(0)) == 0 && new BigDecimal(accvouch.getMd()).compareTo(new BigDecimal(0)) == 0) {
                    i[0]--;
                    return;
                }

                if (!conf.getCcode().equals("100200") || !type.equals("1")) {
                    glAccvouchService.insertGlAccvouch(accvouch);
                    if (StringUtil.isNotEmpty(conf.getCashDesc())) {
                        GlCashtable castable = new GlCashtable();
                        BeanUtil.copyProperties(accvouch, castable);
                        castable.setcCashItem(conf.getCashDesc());
                        cashtableService.insertGlCashtable(castable);
                    }
                }
            });
            item.setiNoId(accvouch.getInoId().toString());
            item.setIflag(1);
            item.setDbillDate(accvouch.getDbillDate());
            ledyTaxService.updateLedyTax(item);
        });
        if (StringUtils.isNotEmpty(accvouch100200.getCcode()) && type.equals("1")) {
            glAccvouchService.insertGlAccvouch(accvouch100200);
            GlCashtable castable = new GlCashtable();
            BeanUtil.copyProperties(accvouch100200, castable);
            cashtableService.insertGlCashtable(castable);
        }
        return toAjax(1);
    }

    /**
     * 查询开票费用凭证列表
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedyTax ledyTax) {
        startPage();
        List<LedyTax> list = ledyTaxService.selectLedyTaxList(ledyTax);
        return getDataTable(list);
    }

    // 导入方法
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<LedyTax> util = new ExcelUtil<>(LedyTax.class);
        List<LedyTax> list = util.importExcel(file.getInputStream());
        String message = ledyTaxService.importTax(list, updateSupport);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<LedyTax> util = new ExcelUtil<>(LedyTax.class);
        util.importTemplateExcel(response, "开票数据");
    }

    /**
     * 导出开票费用凭证列表
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:export')")
    @Log(title = "开票费用凭证", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LedyTax ledyTax) {
        List<LedyTax> list = ledyTaxService.selectLedyTaxList(ledyTax);
        ExcelUtil<LedyTax> util = new ExcelUtil<LedyTax>(LedyTax.class);
        util.exportExcel(response, list, "开票费用凭证数据");
    }

    /**
     * 获取开票费用凭证详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ledyTaxService.selectLedyTaxById(id));
    }

    /**
     * 新增开票费用凭证
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:add')")
    @Log(title = "开票费用凭证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedyTax ledyTax) {
        return toAjax(ledyTaxService.insertLedyTax(ledyTax));
    }

    /**
     * 修改开票费用凭证
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:edit')")
    @Log(title = "开票费用凭证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedyTax ledyTax) {
        return toAjax(ledyTaxService.updateLedyTax(ledyTax));
    }

    /**
     * 删除开票费用凭证
     */
    @PreAuthorize("@ss.hasPermi('erp:tax:remove')")
    @Log(title = "开票费用凭证", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ledyTaxService.deleteLedyTaxByIds(ids));
    }
}
